package com.yssoft.utils;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.stream.FileImageOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 *上传文件公共类
 */
@Component
public class UploadFile {

	private static Logger logger=Logger.getLogger(UploadFile.class);
	private static String WORKDIR;
	private static final String PROGRAM_NAME = "M_";

	@Value("${local_path}")
	public void setWorkdir(String workdir) {
		WORKDIR = workdir;
	}

	/**
	 * 单文件上传.
	 */
	public static synchronized String processUploadedFile(MultipartFile dataFile)  {
		if (StringUtils.isBlank(WORKDIR)) {
			logger.info("系统错误,请设置系统工作目录.");
		}

		String savePath = String.format("%s%s", WORKDIR, File.separatorChar);

		File f = new File(savePath);

		if (!f.exists()) {
			if (!f.mkdirs()) {
				logger.info("系统错误,创建文件保存目录失败,请重试!.");
			}
		}
		//后缀
		String suffix=".png";
		if(dataFile.getOriginalFilename().lastIndexOf(".")>=0){
			suffix = dataFile.getOriginalFilename().substring(dataFile.getOriginalFilename().lastIndexOf("."));
		}
		//文件名+后缀
		String fileName = PROGRAM_NAME+System.currentTimeMillis()+suffix;
		String path = String.format("%s%s%s", f.getAbsolutePath(), File.separatorChar, fileName);

		try {
			dataFile.transferTo(new File(path));
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("保存文件失败:" + e.getMessage());
		}

		return "/files/"+fileName;
	}

	/**
	 * 单文件上传文件.
	 */
	public static synchronized String processUploadedVideo(MultipartFile dataFile)  {
		if (StringUtils.isBlank(WORKDIR)) {
			logger.info("系统错误,请设置系统工作目录.");
		}

		String savePath = String.format("%s%s", WORKDIR, File.separatorChar);

		File f = new File(savePath);

		if (!f.exists()) {
			if (!f.mkdirs()) {
				logger.info("系统错误,创建文件保存目录失败,请重试!.");
			}
		}
		//后缀
		String suffix=".mp4";
		if(dataFile.getOriginalFilename().lastIndexOf(".")>=0){
			suffix = dataFile.getOriginalFilename().substring(dataFile.getOriginalFilename().lastIndexOf("."));
		}
		//文件名+后缀
		String fileName = PROGRAM_NAME+System.currentTimeMillis()+suffix;
		String path = String.format("%s%s%s", f.getAbsolutePath(), File.separatorChar, fileName);

		try {
			dataFile.transferTo(new File(path));
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("保存文件失败:" + e.getMessage());
		}

		return "/files/"+fileName;
	}

	/**
	 * @Description: 将base64编码字符串转换为图片并存储文件
	 * @Author: 陈翼东
	 * @CreateTime:
	 * @param imgStr base64编码字符串
	 * @param path 图片路径-具体到文件
	 * @return
	 * @throws IOException
	 * @throws DecoderException
	 */
	public static synchronized String compressUploadedPicNoCompress(String imgStr) throws IOException, DecoderException {
		imgStr=imgStr.replace("data:image/png;base64,","");
		if (StringUtils.isBlank(WORKDIR)) {
			logger.info("系统错误,请设置系统工作目录.");
		}
		String savePath = String.format("%s%s", WORKDIR, File.separatorChar);
		File f = new File(savePath);

		if (!f.exists()) {
			if (!f.mkdirs()) {
				logger.info("系统错误,创建文件保存目录失败,请重试!.");
			}
		}
		//文件名+后缀
		String fileName = PROGRAM_NAME+System.currentTimeMillis()+".png";
		String path = String.format("%s%s%s", f.getAbsolutePath(), File.separatorChar, fileName);

		byte[] asBytes = Base64.decodeBase64(imgStr);
		byte2image(asBytes,path);
		return  "/files/"+fileName;
	}
	/**
	 * @Title: byte2image
	 * @Description: 存储图片
	 * @return void    返回类型
	 * @author 陈翼东
	 * @CreateDate:   2017年5月18日 下午4:31:39
	 *
	 */
	public static synchronized void byte2image(byte[] data,String path){
		if(data.length<3||path.equals("")) return;//判断输入的byte是否为空
		try{
			FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));//打开输入流
			imageOutput.write(data, 0, data.length);//将byte写入硬盘
			imageOutput.close();
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	/**
	 * 同时上传原图片和压缩后图片
	 * @param dataFile
	 * @return
	 */
	public static synchronized Map<String, Object> compressUploadedFile(MultipartFile dataFile) {
		Map<String, Object> fileNames = new HashMap<String, Object>();
		if (StringUtils.isBlank(WORKDIR)) {
			logger.info("系统错误,请设置系统工作目录.");
		}
		// WORKDIR\
		String savePath = String.format("%s%s", WORKDIR, File.separatorChar);

		File f = new File(savePath);

		if (!f.exists()) {
			if (!f.mkdirs()) {
				logger.info("系统错误,创建文件保存目录失败,请重试!.");
			}
		}

		Long timestamp = System.currentTimeMillis();

		//后缀
		String suffix=".png";
		if(dataFile.getOriginalFilename().lastIndexOf(".")>=0){
			suffix = dataFile.getOriginalFilename().substring(dataFile.getOriginalFilename().lastIndexOf("."));
		}
		//文件名+后缀
		String fileName = PROGRAM_NAME+timestamp+suffix;
		String tFileName = PROGRAM_NAME+"T" + timestamp+suffix;
		String path = String.format("%s%s%s", f.getAbsolutePath(), File.separatorChar, fileName);
		String toPic = String.format("%s%s%s", f.getAbsolutePath(), File.separatorChar, tFileName);
		try {
			dataFile.transferTo(new File(path));
			//按照比例进行缩小和放大
			Thumbnails.of(path).scale(0.5f).toFile(toPic);//按比例缩小
			fileNames.put("fileName", "/files/"+fileName);
			fileNames.put("thumbnails", "/files/"+tFileName);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("保存文件失败:" + e.getMessage());
		}

		return fileNames;
	}




	/**
	 *根据路径删除单个文件
	 */
	public boolean deleteFileByPath(String path){
		File file = new File(path);
		File fileT = new File(path.replace(PROGRAM_NAME, PROGRAM_NAME+"T"));
		try{
			if(file.exists()){
				if(fileT.exists()){
					fileT.delete();
				}
				return file.delete();
			}else{
				return false;
			}
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}

	/**
	 *根据虚拟路径删除单个文件
	 */
	public boolean deleteFileByVirtualPath(String path){
		try{
			String fileName = null;
			int index = path.lastIndexOf(PROGRAM_NAME);
			if(index > -1){
				fileName = path.substring(index);
			}else{
				return false;
			}
			if(StringUtils.isNotBlank(fileName)){
				File file = new File(WORKDIR+File.separator+fileName);
				File fileT = new File(WORKDIR+File.separator+(fileName.replace(PROGRAM_NAME, PROGRAM_NAME+"T")));
				if(file.exists()){
					if(fileT.exists()){
						fileT.delete();
					}
					return file.delete();
				}else{
					return false;
				}
			}else{
				return false;
			}

		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}

	public boolean deleteFileByName(String fileName){
		File file = new File(WORKDIR+File.separator+fileName);
		File fileT = new File(WORKDIR+File.separator+(fileName.replace(PROGRAM_NAME, PROGRAM_NAME+"T")));
		try{
			if(file.exists()){
				if(fileT.exists()){
					fileT.delete();
				}
				return file.delete();
			}else{
				return false;
			}
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
}
